package users

import (
	"context"
	"crypto/md5"
	"dash/jwt"
	"encoding/hex"
	"errors"
	"github.com/go-kit/kit/log"
	"github.com/google/uuid"
)

type UserService interface {
	Login(ctx context.Context, username, pwd string) (string, error)
	Logout(ctx context.Context, username string) error
	Register(ctx context.Context, username, pwd string, roles []string, level string) error
	GetProfile(ctx context.Context, username string) (*User, error)
}

type defaultUserService struct {
	repo       UserRepository
	logger     log.Logger
	jwtService jwt.JWTService
}

func (svc *defaultUserService) GetProfile(ctx context.Context, username string) (*User, error) {
	user, err := svc.repo.GetByUsername(ctx, username)
	if err != nil {
		return nil, err
	}
	if user.Name == nil {
		user.Name = user.Username
	}
	if user.Avatar == nil {
		user.SetAvatar("/avatar/4001.png")
	}
	return user, nil
	//var b = []byte(`{
	//"id": "001",
	//"name": "邓老师",
	//"roles": ["admin"],
	//"weChatId": "dp123456",
	//"avatar": "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif",
	//"workingAddress": "北京 朝阳",
	//"phoneNumber": "18569981109",
	//"collectors": []
	//}`)
	//var user User
	//err := json.Unmarshal(b, &user)
	//if err != nil {
	//	return nil, err
	//}
	//user.SetId(username)
	//return &user, nil
}

func NewUserService(logger log.Logger, repo UserRepository, jwtService jwt.JWTService) *defaultUserService {
	return &defaultUserService{
		repo:       repo,
		jwtService: jwtService,
		logger:     logger,
	}
}

func MD5(text string) string {
	hasher := md5.New()
	hasher.Write([]byte(text))
	return hex.EncodeToString(hasher.Sum(nil))
}

func (svc *defaultUserService) Login(ctx context.Context, username, pwd string) (string, error) {
	user, err := svc.repo.GetByUsername(ctx, username)
	if err != nil || user == nil {
		return "", errors.New("用户名或密码错误")
	}
	pwd = MD5(pwd)
	if *user.Password != pwd {
		return "", errors.New("用户名或密码错误")
	}
	if user.Id == nil {
		return "", errors.New("该用户缺少id")
	}
	claims := jwt.NewCustomClaims(*user.Id, username, user.Roles)
	token, err := svc.jwtService.CreateToken(*claims)
	if err != nil {
		return "", err
	}
	return token, nil
}

func (svc *defaultUserService) Logout(_ context.Context, _ string) error {
	return nil
}

func (svc *defaultUserService) Register(ctx context.Context, username, password string, roles []string, level string) error {
	u, err := uuid.NewRandom()
	if err != nil {
		_ = svc.logger.Log("generate uid error:", err)
		return errors.New("网络出现问题,请重试")
	}
	uid := u.String()
	if len(username) == 0 || len(password) == 0 || len(roles) == 0 || len(level) == 0 {
		return errors.New("请提交完整信息")
	}
	user := new(User).SetId(uid).SetUsername(username).SetPassword(password).SetLevel(level)
	//TODO 检查roles是否合法
	user.Roles = roles
	err = svc.repo.Save(ctx, user)
	if err != nil {
		return err
	}
	return nil
}
